package com.eascs.dubbo.api.internal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.form.UserDemandForm;
import com.eascs.admin.api.internal.RequestDemandService;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
/*
 * 需求申请
 */
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.context.ConfigContext;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.demand.entity.EntityUtil;
import com.eascs.demand.entity.MainApply;
import com.eascs.demand.entity.UserDemand;
import com.eascs.demand.entity.UserDemandApplyComment;
import com.eascs.demand.service.DemandApplyCommentService;
import com.eascs.demand.service.DemandService;
import com.eascs.demand.service.OldOaService;
import com.eascs.demand.service.TicketMainApplyService;
import com.eascs.dubbo.api.util.UserUtils;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.EmployeeService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class RequestDemandServiceImpl implements RequestDemandService{
	private static Logger log = LoggerFactory.getLogger(RequestDemandServiceImpl.class);
	/*****************数字常量****************/
	public static final int O2O_SEQUENCE_LENGTH=5;
	
	@Inject
	private OldOaService oldOaService;
	
	@Autowired
	private BaseUserUtil userUtils;
	
	@Reference
	EmployeeService employeeService;
	@Reference
	SysOrgService sysOrgService;
	@Reference
	private SequenceService sequenceService;
	
	@Inject
	private DemandService demandService;
	
	@Inject
	TicketMainApplyService ticketMainApplyService;
	
	@Autowired
	O2oPubDdItemService ddItemService;
	
	@Reference
	private WorkFlowService workFlowService;
	
	@Autowired
	DemandApplyCommentService demandApplyCommentService;
	
	
	@Override
	public void saveDemandInfo(UserDemandForm userDemand) {
		List<Object[]> data = new ArrayList<>();
		String workeara="system";
		data = oldOaService.getOperatorWorkeara(userDemand.getDemandUserid());
		if (data.size()>0) {
			 workeara = data.get(0)[0].toString();	
		}
		String  billCode = buildCode("PDR", workeara);
		userDemand.setBillCode(billCode);
		String uuid = UUID.randomUUID().toString(); 
		userDemand.setId(uuid);
		//插入创建者
		userDemand.setCreator(userUtils.getUserName());
		//插入创建者id
		userDemand.setCreatorId(userUtils.getCreateOr());
		//插入状态  未删除 N
		userDemand.setIslock("N");
		userDemand.setStatus(StatusContexts.O2O_NEW);
		//插入修改者
		userDemand.setUpdator(userUtils.getUserName());
		//插入修改者id
		userDemand.setUpdatorId(userUtils.getCreateOr());
		//插入创建时间
		userDemand.setCreateDate(new Date());
		//插入修改时间
		userDemand.setUpdateDate(new Date());
		User user=employeeService.getUserByNo(userDemand.getDemandUserid());
		if (user!=null) {
			userDemand.setDepname(user.getNodenamecn());
		}
		
		//插入流程表主表
		MainApply mainApply = new MainApply();
		//扩展id
		mainApply.setExpandId(uuid);
		//需求单据编号
		mainApply.setBillCode(billCode);
		ModelResult<ActOrgEntity> modelResult = sysOrgService.getUniquePlatformWithUser(userDemand.getDemandUserid());
		if (!modelResult.isSuccess()) {
			log.info("需求单据错误{}", modelResult.getErrMsg());
			return ;
		}
		mainApply.setLtd(modelResult.getModel().getUnitNo());
//		mainApply.setLtd(demandService.getLtdByUserNo(userDemand.getDemandUserid()));
		mainApply.setOperatorNo(userDemand.getDemandUserid());
		mainApply.setOperatorName(userDemand.getDemandUser());
		mainApply.setBillStatus(StatusContexts.O2O_NEW);
		mainApply.setCreator(userUtils.getUserName());
		mainApply.setCreatorId(userUtils.getCreateOr());
		mainApply.setCreateDate(new Date());
		mainApply.setUpdateDate(new Date());
		mainApply.setUpdator(userUtils.getUserName());
		mainApply.setUpdatorId(userUtils.getCreateOr());
		mainApply.setIslock("N");
		demandService.insertDemandAll(userDemand, mainApply);
		
	}
	
	/**
	 * 生成贷款编号
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	public String buildCode(String code, String type) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + type + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, O2O_SEQUENCE_LENGTH, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}

	@Override
	public UserDemandForm getEntityById(String id) {
		return demandService.getById(UserDemandForm.class, id);
	}

	@Override
	public void updateDemandInfo(UserDemandForm userDemand) {
		//修改需求表相关制字段
				UserDemand demandUpdate = demandService.getUserDemandById(userDemand.getId());
				demandUpdate.setTitle(userDemand.getTitle());
				demandUpdate.setDemandUser(userDemand.getDemandUser());
				demandUpdate.setDemandUserid(userDemand.getDemandUserid());
				User user=employeeService.getUserByNo(userDemand.getDemandUserid());
				if (user!=null) {
					demandUpdate.setDepname(user.getNodenamecn());
				}
				demandUpdate.setDemandType(userDemand.getDemandType());
				demandUpdate.setDueDate(userDemand.getDueDate());
				demandUpdate.setDemandText(userDemand.getDemandText());
				EntityUtil.initUpdateEntity(demandUpdate);
				//修改主表
				MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(userDemand.getId());
				ModelResult<ActOrgEntity> modelResult = sysOrgService.getUniquePlatformWithUser(userDemand.getDemandUserid());
				if (!modelResult.isSuccess()) {
					log.info("需求单据错误{}", modelResult.getErrMsg());
					return ;
				}
				mainApply.setLtd(modelResult.getModel().getUnitNo());
//				mainApply.setLtd(demandService.getLtdByUserNo(userDemand.getDemandUserid()));
				mainApply.setOperatorNo(userDemand.getDemandUserid());
				mainApply.setOperatorName(userDemand.getDemandUser());
				mainApply.setUpdateDate(new Date());
				mainApply.setUpdator(userUtils.getUserName());
				mainApply.setUpdatorId(userUtils.getCreateOr());
				//demandService.updateMainApplyById(mainApply);
				demandService.updateAll(mainApply, demandUpdate);
		
	}

	@Override
	public String startUp(String id) {
		MainApply mainApply = ticketMainApplyService.findMainApplyByExpandId(id);
		UserDemand demand = demandService.getUserDemandByBillcode(mainApply.getBillCode());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(mainApply.getMainapplyNo());
		param.setReferCode(mainApply.getBillCode());
		param.setReferUrl(ConfigContext.getStringValue("o2o.demand.approvalUrl")+"&mainapplyNo="+mainApply.getMainapplyNo());
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		String demandType = demand.getDemandType();
		//如果是系统需求申请：系统错误、系统咨询、单据修改、其它
		String itemtype=ddItemService.findPubdditemO2ONameByCode("SYSDEMANDTYPE", demandType);
		if("SYSERR".equals(demandType) || "XTZX".equals(demandType) || "DJXG".equals(demandType) || "OTH".equals(demandType) || "EXDATA".equals(demandType)){
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_REQUIREMENT_APP);
			if ("SYSERR".equals(demandType) || "XTZX".equals(demandType) || "DJXG".equals(demandType) || "OTH".equals(demandType)) {
				List<String> deleteParmList=new ArrayList<String>();
				deleteParmList.add("O2OCEO");
				param.setExcludeNodeCodeList(deleteParmList);
			}
		}else if("QXCL".equals(demandType) || "GNBG".equals(demandType) || "MBI".equals(demandType)){
			//如果是业务需求申请：权限处理，功能新增/变更/建议，基础信息维护
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_BUS_REQUIREMENT_APP);
			List<String> deleteParmList=new ArrayList<String>();
			if (!"QXCL".equals(demandType)) {
				deleteParmList.add("node_hrfzr");
			}
			param.setExcludeNodeCodeList(deleteParmList);
		}else if("DJZF".equals(demandType)){
			//如果是需求申请（只需要过总部领导的）:作废
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_HQ_REQUIREMENT_APP);
		}else if("SYSDEVELOP".equals(demandType)){
			//如果是系统开发
			param.setProcessType(ProcessTemplate.PROECESS_TYPE_SYSTEM_DEV);
		}else if (!StringUtils.isEmpty(itemtype)) {
			param.setProcessType(demandType);
		}
		param.setProcessVersion("v1");
		param.setAppliedby(demand.getDemandUserid());
		//param.setAppliedbyName(mainApply.getCreator());//
		param.setAppliedbyName("申请人：" + demand.getDemandUser());
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		roleUserMap.put(StatusContexts.LOAN_TYPE_PTJL_ROLE, Arrays.asList(mainApply.getOperatorNo()));  //最后一个节点，动态指定经办人
		//如果提交人是总部的人，省区负责人设置为自己
		if("24793".equals(mainApply.getLtd())){
			roleUserMap.put(StatusContexts.LOAN_TYPE_JRZJ_ROLE, Arrays.asList(mainApply.getOperatorNo()));
		}
		param.setRoleUserMap(roleUserMap);
		param.setOrgNo(mainApply.getLtd());
		User user = UserHolder.getUser();
		param.setLoginUser(UserUtils.getUser(user));
		//摘要
		param.setAppliedDes("需求申请：" + demand.getTitle());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				ticketMainApplyService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_RUN, mainApply.getMainapplyNo());
				return null;
			} else {
				return modelResult.getErrMsg();
			}
	}

	@Override
	public void saveExtraInfo(String billCode,String commentContent) {
		UserDemandApplyComment comment=new UserDemandApplyComment();
		User user = UserHolder.getUser();
		comment.setCreateDate(new Date());
		comment.setCreator(user.getCode());
		comment.setCreatorName(user.getCname());
		comment.setUpdateDate(new Date());
		comment.setUpdator(user.getCode());
		comment.setUpdatorName(user.getCname());
		comment.setCommentContent(commentContent);
		comment.setBillCode(billCode);
		demandApplyCommentService.insert(comment);
		
	}
}
